import Vue from "vue";
var vm = new Vue();
// import {
// 	Websocketbind
// } from '../../api/IM.js';
var webSocketData = {
	isWebSocketConnected: false,
	heartbeatInterval: null
};
/** 
@method 开始进行WebSocket连接
**/
export const linkSocket = () => {
	uni.connectSocket({
		url: getApp().globalData.newsocket_url,
		success() {
			console.log('WebSocket连接成功');
			MonitorWebSocketStatus();
		},
		fail(error) {
			console.log('WebSocket连接失败正在准备重新连接------------》', error);
			//连接失败2秒后进行重连
			setTimeout(linkSocket(), 2000);
		}
	});
}

/** 
@TODO: 接收到消息此方法才执行
@method 监听WebSocket消息返回
**/
export const MonitorWebSocket = () => {
	console.log('WebSocket消息开始监听------------》');
	uni.onSocketMessage((res) => {
		let webSocketMessage = JSON.parse(res.data);
		if (webSocketMessage.hasOwnProperty('message_type') == true) {
			switch (webSocketMessage.message_type) {
				case 'init': //初始化	
					console.log('初始化WebSocket成功-------------》');
					console.log('开始进行聊天对象绑定-------------》');
					if (webSocketMessage.kefu_info[0].user_id !== uni.getStorageSync('userInfo').id) {
						handleWebSocketMessage({
							message_type: 'init',
							data: {
								fromid: webSocketMessage.kefu_info[0].user_id,
								content: webSocketMessage.kefu_info[0].remark,
								head_img: webSocketMessage.kefu_info[0].head_img,
								id: webSocketMessage.kefu_info[0].id,
								message_id: webSocketMessage.kefu_info[0].id,
								type: "friend",
								update_time: new Date().getTime(),
								username: webSocketMessage.kefu_info[0].kusername,
							}
						});
					}

					// Websocketbinding(webSocketMessage.client_id);
					//客服id
					uni.setStorageSync('init_id', webSocketMessage.kefu_info[0].user_id);
					//连接凭证
					uni.setStorageSync('client_id', webSocketMessage.client_id);
					break;
				case 'close': //连接中连接状态异常
					console.log('WebSocket连接状态异常1秒后进行重连-------------》');
					setTimeout(linkSocket(), 1000);
					break;
				case 'chatMessage': //收到用户 || 客服的聊天消息
					console.log('WebSocket监听到了-------------》');
					console.log(JSON.parse(res.data));
					handleWebSocketMessage(JSON.parse(res.data));
					break;
				case 'logMessage': //历史记录返回
					handleWebSocketMessage(JSON.parse(res.data));
					break;
			}
		} else {
			if (webSocketMessage.hasOwnProperty('type') == true) {
				switch (webSocketMessage.type) {
					case 'ping': //连接中连接状态异常
						console.log('WebSocket连接状态正常-------------》');
						break;
				}
			}
		}
		console.log('接收到WebSocket消息', JSON.parse(res.data));
	});
}

/** 
@TODO: null
@method 处理WebSocket返回的信息
**/
export const handleWebSocketMessage = (message = {}) => {
	// console.log("获取store里面的存储websocket数据--------------》");
	vm.$store.dispatch('websocket/receiveWebsocketMessage', [message.data]);
	vm.$store.dispatch('websocket/updateArray', [message.data]);
}

/** 
@TODO: null
@method 监听WebSocket关闭还是开启状态
**/
export const MonitorWebSocketStatus = () => {
	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！------------》');
		MonitorWebSocket();
		webSocketData.isWebSocketConnected = true;
		startHeartbeat();
	});

	uni.onSocketClose((res) => {
		console.log('WebSocket连接已被关闭！------------》');
		console.log(res);
		webSocketData.isWebSocketConnected = false;
		stopHeartbeat();
		console.log('WebSocket连接已被关闭2秒后进行重新连接！------------》');
		setTimeout(linkSocket(), 2000);
		uni.removeStorageSync('client_id');
	});
	
	uni.onSocketError(function(res) {
		console.log('WebSocket连接打开失败，请检查！------------》');
		console.log('WebSocket连接打开失败2秒后进行重新连接！------------》');
		setTimeout(linkSocket(), 2000);
		uni.removeStorageSync('client_id');
	});
}

/** 
@TODO: null
@method 聊天用户信息绑定
**/
export const Websocketbinding = async (e = {}) => {
	try {
		const res = await Websocketbind({
			client_id: e
		});
		if (res.success == true || res.success == 'true') {
			let newMessage = {
				client_id: uni.getStorageSync('client_id'),
				data: {
					message_type: 'init', //message 发文本信息 用户  客服,
					username: uni.getStorageSync('userInfo').username,
					head_img: uni.getStorageSync('userInfo').head_img,
					id: uni.getStorageSync('userInfo').id,
					message_id: '',
				}
			};
			uni.sendSocketMessage({
				data: JSON.stringify(newMessage),
				success() {
					console.log('WebSocket消息发送成功------------》');
				},
				fail(error) {
					console.log('WebSocket消息发送失败------------》');
					console.log(error);
				}
			});
			console.log('聊天对象绑定成功----------》');
		}
	} catch (err) {
		//TODO handle the exception
		console.log(err);
	}
}

/** 
@method 开始心跳监听websocket连接状态监听逻辑则是每隔30秒向socket发送一次消息从而实现监听
**/
export const startHeartbeat = () => {
	webSocketData.heartbeatInterval = setInterval(() => {
		if (webSocketData.isWebSocketConnected) {
			uni.sendSocketMessage({
				data: 'ping', // 发送心跳数据
				success(res) {
					console.log('正在心跳监听每100毫秒一次');
				},
				fail() {
					//连接失败2秒后进行重连
					setTimeout(linkSocket(), 2000);
					stopHeartbeat();
				}
			});
		} else {
			stopHeartbeat();
		}
	}, 100); // 100毫秒发送一次心跳
}

/** 
@method 心跳监听终止
**/
export const stopHeartbeat = () => {
	clearInterval(webSocketData.heartbeatInterval);
	// uni.closeSocket();
}

/** 
@method 关闭 WebSocket 连接
**/
export const closeSocket = () => {
	uni.closeSocket({
		success() {
			console.log('WebSocket 连接已关闭');
		},
		fail(err) {
			console.error('关闭 WebSocket 连接失败', err);
		},
	});
}